package com.leyou.auth.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.auth.config.OSSProperties;
import com.leyou.auth.dto.AliOssSignatureDTO;
import com.leyou.auth.service.AliAuthService;
import com.leyou.common.exceptions.LyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;

/**
 * @author 虎哥
 */
@Service
public class AliAuthServiceImpl implements AliAuthService {

    @Autowired
    private OSS ossClient;
    @Autowired
    private OSSProperties prop;

    @Override
    public AliOssSignatureDTO getAliOssSignature() {
        try {
            // 签名的有效时间，单位是秒
            long expireTime = prop.getExpireTime();
            // 计算到期的时间
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // 对文件上传的限制策略，例如：文件大小限制、上传位置的限制
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            // 对限制策略做编码，转为字符串
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 计算签名
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            return AliOssSignatureDTO.of(
                    prop.getAccessKeyId(), prop.getHost(),
                    encodedPolicy, postSignature,
                    expireEndTime , prop.getDir());
        } catch (Exception e) {
            throw new LyException(500, "签名授权异常", e);
        }
    }
}
